#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#   File: db.py
#   Author: Finnur Smári Torfason
#   Date: 29/12/2011
#
#   Sér um gagnagrunninn

#import afla_func as afla
import sqlite3, os.path, wx, shutil
from utils import helpers
from event import ResultEvent

#
# Fallið nær í upplýsingar um báta, ef ekki hefur verið valið að
# uppfæra skipaskrárnúmer
#
def getShipInfo(kvtime):
  con = sqlite3.connect('./db/aflalisti.sql')
  cur = con.cursor()
	
  cur.execute("SELECT * FROM boat WHERE kvtime='" + kvtime + "'")
  shipInfo = cur.fetchall()
	
  cur.close()
  con.close()
	
  return shipInfo

#
# Ef gagnagrunnurinn er ekki til, er hann bara
# búinn til.
#
def checkDbExists():
  if not os.path.exists('./db/aflalisti.sql'):
    con = sqlite3.connect('./db/aflalisti.sql')
    cur = con.cursor()
    cur.executescript("""
			create table boat(
				id not null,
				name, 
				size,
				category,
				landing,
				kvtime not null,
				PRIMARY KEY (id, kvtime)
			);

			create table landing(
				id,
				url not null primary key,
				date,
				gear,
				harbour,
				total,
				ftype,
				ftot, 
				kvtime
			);
			""")
		
    # Save and close the cursor and connection
    con.commit()
    cur.close()
    con.close()
    return 0
  return 1

#
# Hér er skrifað í töflur
#
def writeToDB(shipInfo, landingInfo, kvtime, notify_window):
  writeToTableBoat(shipInfo, kvtime, notify_window)
  writeToTableLanding(landingInfo, kvtime, notify_window)
  shutil.copy('./db/aflalisti.sql', './db/.backup/aflalisti.sql')

#
# Hér er skrifað í boat töfluna
#
def writeToTableBoat(boatInfo, kvtime, notify_window):
  con = sqlite3.connect('./db/aflalisti.sql')
  cur = con.cursor()
  con.text_factory = str
	
  wx.PostEvent(notify_window, ResultEvent('\nSkrifa upplýsingar um bát í boat töfluna\n', 0))
  # Skrifum í boat töfluna
  for i in boatInfo:
    try: 
      cur.execute("""INSERT INTO boat (id, name, size, category, landing, kvtime)
										 VALUES
										 (?,?,?,?,?,?)""", i)
      con.commit()
    except (sqlite3.IntegrityError):
      updText = "UPDATE boat SET landing='%s' WHERE id='%s' AND kvtime='%s'" % (i[4], i[0], i[5])
      cur.execute(updText)
      con.commit()

  cur.close()
  con.close()
#
# Hér er skrifað í landing töfluna
#
def writeToTableLanding(landingInfo, kvtime, notify_window): 
  con = sqlite3.connect('./db/aflalisti.sql')
  cur = con.cursor()
  con.text_factory = str

  for i in landingInfo:
    try:
      cur.execute("""INSERT INTO landing (id, url, date, gear, harbour, total, ftype, ftot, kvtime)
										 VALUES
										 (?,?,?,?,?,?,?,?,?)""", i)
      con.commit()
    except (sqlite3.IntegrityError):
      updText = "UPDATE landing SET total='%s', ftype='%s', ftot='%s', kvtime='%s' WHERE url='%s'" % (i[5], i[6], i[7], i[8], i[1])
      cur.execute(updText)
      con.commit()

  cur.close()
  con.close()

#
# Fallið nær í upplýsingar um báta, ef ekki hefur verið valið að
# uppfæra skipaskrárnúmer
#
def getShipInfo(kvtime):
  con = sqlite3.connect('./db/aflalisti.sql')
  cur = con.cursor()

  cur.execute("SELECT * FROM boat WHERE kvtime='" + kvtime + "'")
  shipInfo = cur.fetchall()

  cur.close()
  con.close()

  return shipInfo

#
# Fallið sækir lista af löndunum báts 
#
def getLandingList(kvtime, boatId):
  
  # Tengist gagnagrunni
  con = sqlite3.connect('./db/aflalisti.sql')
  cur = con.cursor()
  
  # sæki landanir
  cur.execute("SELECT * FROM landing WHERE kvtime='" + kvtime + "' AND id=" + boatId)
  landingList = cur.fetchall()


  return landingList

